/**
 * Created by Toma on 2016/10/14.
 */

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var WIDTH = ctx.canvas.width;
var HEIGHT = ctx.canvas.height;
var R = WIDTH / 2;
var REM = WIDTH / 200;

function drowBackground() {
  ctx.translate(R, R);

  ctx.beginPath();
  ctx.lineWidth = 10 * REM;
  ctx.strokeStyle = '#000';
  ctx.arc(0, 0, R - ctx.lineWidth / 2, 0, 2 * Math.PI, false);
  ctx.stroke();

  var hourNumbers = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2];
  ctx.font = 18 * REM + 'px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  hourNumbers.forEach(function (num, i) {
    var rad = 2 * Math.PI / 12 * i;
    var x = Math.cos(rad) * (R - 30*REM);
    var y = Math.sin(rad) * (R - 30*REM);
    ctx.fillText(num, x, y);
  });

  for (var i = 0; i < 60; i++) {
    var rad = 2 * Math.PI / 60 * i;
    var x = Math.cos(rad) * (R - 18*REM);
    var y = Math.sin(rad) * (R - 18*REM);
    ctx.beginPath();
    if (i % 5 === 0) {
      ctx.fillStyle = '#000';
      ctx.arc(x, y, 2*REM, 0, 2 * Math.PI, false);
    } else {
      ctx.fillStyle = '#ccc';
      ctx.arc(x, y, 2, 0, 2 * Math.PI, false);
    }
    ctx.fill();
  }
}

function drawHour(hour, min) {
  ctx.save();
  ctx.beginPath();
  var rad = 2 * Math.PI / 12 * hour;
  var mrad = 2 * Math.PI / 12 / 60 * min;
  ctx.rotate(rad + mrad);
  ctx.lineWidth = 6*REM;
  ctx.lineCap = 'round';
  ctx.moveTo(0, 10*REM);
  ctx.lineTo(0, -R / 2);
  ctx.stroke();
  ctx.restore();
}

function drawMinte(min) {
  ctx.save();
  ctx.beginPath();
  var rad = 2 * Math.PI / 60 * min;
  ctx.rotate(rad);
  ctx.lineWidth = 3*REM;
  ctx.lineCap = 'round';
  ctx.moveTo(0, 10*REM);
  ctx.lineTo(0, -R + 30*REM);
  ctx.stroke();
  ctx.restore();
}

function drawSecound(sec) {
  ctx.save();
  ctx.beginPath();
  var rad = 2 * Math.PI / 60 * sec;
  ctx.rotate(rad);
  ctx.lineWidth = 3*REM;
  ctx.lineCap = 'round';
  ctx.fillStyle = 'red';
  ctx.moveTo(-2, 20*REM);
  ctx.lineTo(2, 20*REM);
  ctx.lineTo(1, -R + 20*REM);
  ctx.lineTo(-1, -R + 20*REM);
  ctx.fill();
  ctx.restore();
}

function drawDot() {
  ctx.beginPath();
  ctx.fillStyle = 'red';
  ctx.arc(0, 0, 4*REM, 0, 2 * Math.PI, false);
  ctx.fill();
}

function draw() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
  var now = new Date();
  var hour = now.getHours();
  var min = now.getMinutes();
  var sec = now.getSeconds();
  ctx.save();
  drowBackground();
  drawHour(hour, min);
  drawMinte(min);
  drawSecound(sec);
  drawDot();
  ctx.restore();
  setTimeout(draw, 1000);
}

draw();